﻿using LPP.Entity.Addresses;
using LPP.EntityFrameworkCore;
using LPP.Repository.AddressRepository;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace LPP.Service.AddressService
{
    public class AddressService : IAddressService
    {
        private readonly IAddressRepository _addressRepository;
        private readonly SqlDbContext _context;
        private readonly ILogger<AddressService> _logger;

        public AddressService(
            IAddressRepository addressRepository,
            SqlDbContext context,
            ILogger<AddressService> logger)
        {
            _addressRepository = addressRepository;
            _context = context;
            _logger = logger;
        }

        /// <summary>
        /// 获取用户的地址列表
        /// </summary>
        public async Task<List<Address>> GetAddressAsync(int userId)
        {
            try
            {
                _logger.LogInformation($"正在获取用户 {userId} 的地址列表");
                var addresses = await _addressRepository.GetAddressesByUserIdAsync(userId);

                if (!addresses.Any())
                {
                    _logger.LogInformation($"用户 {userId} 没有保存的地址");
                }

                return addresses;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取用户 {userId} 的地址列表时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 添加新地址
        /// </summary>
        public async Task<bool> AddAddressAsync(Address address)
        {
            try
            {
                if (address == null)
                {
                    throw new ArgumentNullException(nameof(address));
                }

                _logger.LogInformation($"正在为用户 {address.UserID} 添加新地址");

                // 验证用户是否存在
                var userExists = await _context.Users.AnyAsync(u => u.UserID == address.UserID);
                if (!userExists)
                {
                    _logger.LogWarning($"用户 {address.UserID} 不存在");
                    throw new Exception("用户不存在");
                }

                // 验证必要字段
                if (string.IsNullOrEmpty(address.City) ||
                    string.IsNullOrEmpty(address.AddressDetail) ||
                    string.IsNullOrEmpty(address.ContactName) ||
                    string.IsNullOrEmpty(address.PhoneNumber))
                {
                    throw new ArgumentException("地址信息不完整");
                }

                await _addressRepository.AddAddressAsync(address);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加地址时发生错误: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 更新地址
        /// </summary>
        public async Task<bool> UpdateAddressAsync(Address address)
        {
            try
            {
                _logger.LogInformation($"正在更新地址 ID {address.AddressID}");

                var existingAddress = await _context.Addresses
                    .FirstOrDefaultAsync(a => a.AddressID == address.AddressID);

                if (existingAddress == null)
                {
                    _logger.LogWarning($"未找到要更新的地址 ID {address.AddressID}");
                    return false;
                }

                // 更新地址信息
                existingAddress.City = address.City;
                existingAddress.AddressDetail = address.AddressDetail;
                existingAddress.BuildingNumber = address.BuildingNumber;
                existingAddress.ContactName = address.ContactName;
                existingAddress.PhoneNumber = address.PhoneNumber;

                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新地址时发生错误: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 删除地址
        /// </summary>
        public async Task<bool> DeleteAddressAsync(int addressId)
        {
            try
            {
                _logger.LogInformation($"正在删除地址 ID {addressId}");

                var address = await _context.Addresses
                    .FirstOrDefaultAsync(a => a.AddressID == addressId);

                if (address == null)
                {
                    _logger.LogWarning($"未找到要删除的地址 ID {addressId}");
                    return false;
                }

                _context.Addresses.Remove(address);
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除地址时发生错误: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 获取地址详情
        /// </summary>
        public async Task<Address> GetAddressDetailAsync(int addressId)
        {
            try
            {
                _logger.LogInformation($"正在获取地址 ID {addressId} 的详情");

                var address = await _context.Addresses
                    .FirstOrDefaultAsync(a => a.AddressID == addressId);

                if (address == null)
                {
                    _logger.LogWarning($"未找到地址 ID {addressId}");
                }

                return address;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取地址详情时发生错误: {ex.Message}");
                throw;
            }
        }
    }
}
